from typing import List, Union

from fastapi import APIRouter
from fastapi.exceptions import HTTPException
from models import *
from pydantic import BaseModel
from tortoise import transactions

student = APIRouter()


@student.get("/student")
async def getAllStudent():
    # values相当于select xxx form 中的xxx字段
    # students = await Student.all().values("name", "sno", "clas__name")
    # contains相当于 like
    students = await Student.filter(name__contains='s').values("name", "clas__name")
    print("students", students)
    # get相当于 = 操作
    student1 = await Student.get(id=1)
    print(student1.name)
    return students


class StudentModel(BaseModel):
    name: str
    pwd: str
    sno: int
    clas_id: Union[int, None] = None
    courses: List[int] = []


@student.post("/student")
async def addStudent(stu: StudentModel):
    # 添加数据库操作
    # 方式1
    # student = Student(name=stu.name, pwd=stu.pwd, sno=stu.sno, clas_id=stu.clas)
    # await student.save()
    # 方式2
    student = await Student.create(name=stu.name, pwd=stu.pwd, sno=stu.sno, clas_id=stu.clas_id)
    print(student, dir(student))

    # 添加多对多关系记录
    courses = await Course.filter(id__in=stu.courses)
    print("courses", courses)
    await student.courses.add(*courses)
    print("student", student.courses)

    return student


@student.put("/student/{student_id}")
async def update_student(student_id: int, student: StudentModel):
    data = student.model_dump(exclude_unset=True)
    courses = data.pop("courses")
    print(data, courses)
    await Student.filter(id=student_id).update(**data)

    courses = await Course.filter(id__in=student.courses)
    edit_student = await Student.get(id=student_id)
    await edit_student.courses.clear()
    await edit_student.courses.add(*courses)

    return student


@student.delete("/student/{student_id}")
async def delete_student(student_id: int):
    deleted_count = await Student.filter(id=student_id).delete()  # 条件删除
    if not deleted_count:
        raise HTTPException(status_code=404, detail=f"Student {student_id} not found")
    return {}


# 事务操作：同时创建学生和课程
@student.post("/transaction/student_course")
async def transaction_student_course():
    async with transactions.in_transaction() as connection:
        try:
            new_student = await Student.create(name="New Student", pwd="123456", sno=1001, clas_id=1,
                                               using_db=connection)
            new_course = await Course.create(name="New Course", teacher_id=1, address="Room 101", using_db=connection)
            await new_student.courses.add(new_course)
            return {"message": "Transaction successful", "student_id": new_student.id, "course_id": new_course.id}
        except Exception as e:
            return {"message": f"Transaction failed: {str(e)}"}
